package com.algorithm.dp;

/**
 * 给定一个包含非负整数的 m x n 网格，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。
 * <p>
 * 说明：每次只能向下或者向右移动一步。
 * <p>
 * 转移方程 dp[i][j] = min{dp[i-1][j],dp[i][j-1]}
 * i,j表示从数组左上角到i行j列需要的最小路径
 */
public class MinPathSum {
    public static void main(String[] args) {
        int[][] grid =
                {
                        {1, 3, 1},
                        {1, 5, 1},
                        {4, 2, 1}
                };
        System.out.println(minPathSum(grid));
        System.out.println(minPathSum1(grid));
    }

    public static int minPathSum(int[][] grid) {
        int rowLen = grid.length;
        int colLen = grid[0].length;
        int[][] dp = new int[rowLen][colLen];
        dp[0][0] = grid[0][0];
        for (int i = 1; i < rowLen; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int i = 1; i < colLen; i++) {
            dp[0][i] = dp[0][i - 1] + grid[0][i];
        }
        for (int i = 1; i < rowLen; i++) {
            for (int j = 1; j < colLen; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }

        return dp[rowLen - 1][colLen - 1];
    }

    /**
     * 优化为一维数组
     *
     * @param grid
     * @return
     */
    public static int minPathSum1(int[][] grid) {
        if (grid.length == 0){
            return 0;
        }
        int length = grid.length;
        int[] dp = new int[length];
        dp[0] = grid[0][0];
        for (int i = 1; i < length; i++) {
            dp[i] = dp[i - 1] + grid[i][0];
        }
        for (int j = 1; j < grid[0].length; j++) {
            for (int i = 0; i < length; i++) {
                if (i == 0){
                    dp[i] = dp[i] + grid[i][j];
                }else {
                    dp[i] = Math.min(dp[i - 1], dp[i]) + grid[i][j];
                }
            }
        }
        return dp[length - 1];
    }
}
